/// <reference types="jquery">
import i18n from '@/lang'
import axios from "axios";
import { serialize, noEmptyOfObject } from "@/utils/util";
import Cancel from './cancelToken.js'
import NProgress from "nprogress"
import "nprogress/nprogress.css";
import { errorCode,authCode,authErrorCode } from "@/const/errorCode.js";
import router from "@/router";
import { decryption } from "@/utils/util";
import {deCodeKey} from "@/const/const";
import eventBus from "@/utils/eventBus";
import { ElNotification } from 'element-plus'
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 600000,
});

NProgress.configure({
    showSpinner: false
});
let countTime = 0
const freshTokenUrl = '/auth/oauth2/token'
let currentRoutePath = '' // 当前路由
let lastUrl = ''
const whiteApi = ['/auth/token/logout']
import upgradeDialog from '@/utils/upgrade'
import { mobileMessage } from '@/utils/mobileMessage'

// 判断是否手机端
let isMobile = ()=>{
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    let isMobile = sessionStorage.getItem('isMobile') || 0
    return flag || !!isMobile;
}

import useUserInfoStore from "@/store/userInfo.js";

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserInfoStore()
    // 在这里可以根据业务需求设置请求header，包括token等
    // NProgress.start()
    const isToken = (config.headers || {}).isToken === false;
    let token = userStore.access_token;
    if (token && !isToken) {
        config.headers["Authorization"] = 'Bearer ' + token;
    }
    if(config.url.indexOf('/upload/')!=-1){
        config.timeout = pluginConfig.fileDownloadTime
    }
    const {locale} = i18n.global
    config.headers['Accept-Language'] = locale.value
    // 添加请求头 固定参数
    config.headers["jvs-rule-ua"] = encodeURI('2.1.9')
    // config.headers["jvs-rule-ua"] = encodeURI('default')
    // headers中配置serialize为true开启序列化 文件
    if (config.methods === "post" && config.headers.serialize) {
        config.data = serialize(config.data);
        delete config.data.serialize;
    }
    // 去除空值参数
    if (config.params) {
    config.params = noEmptyOfObject(config.params)
    }
    if (config.data && config.headers['type']!='FormData') {
    config.data = noEmptyOfObject(config.data)
    }
    let config1 = config
    // 是否需要防重复提交中断请求
    if(!config.isNotCancel && router.currentRoute.value.path != '/designoffice'){
        Cancel.removePending(config);
        config1 = Cancel.addPending(config);
    }
    return config1;
  },
  (err) => {
    return Promise.reject(err);
  }
);
 
// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    const userStore = useUserInfoStore()
    const { t } = i18n.global;

    // 这里根据业务需求对响应进行处理，可以根据响应状态码进行不同的处理
    NProgress.done();
    const status = Number(res.status) || 200;
    const message = res.data.msg || errorCode[res.status] || errorCode["default"];
    if(router.currentRoute.value.path !== currentRoutePath) {
        currentRoutePath = router.currentRoute.value.path
        lastUrl = location.href
        window.parent.postMessage({command: 'isIndex'}, '*')
    }
    // 401为没有权限的情况
    if (status === 401) {
        userStore.LogOut().then(() => {
            sessionStorage.setItem('lastUrl', lastUrl)
            if(router.currentRoute.value && router.currentRoute.value.path != '/') {
                router.push({ path: "/" });
            }
        });
        return;
    }
    if (status !== 200 || res.data.code === 1) {
        if(router.currentRoute.value.path== '/designoffice'){
            userStore.LogOut().then(() => {
                sessionStorage.setItem('lastUrl', lastUrl)
                if(router.currentRoute.value && router.currentRoute.value.path != '/') {
                    router.push({ path: "/" });
                }
            });
            return;
        }
        if(res.config.url == freshTokenUrl) {
            if(res.config.params && !res.config.params.switch) {
                if(!res.config.isReturn){
                    if(isMobile()){
                        mobileMessage.closeAll()
                        mobileMessage.install({
                            text:message,
                            type:'error'
                        })
                    }else{
                        ElNotification.closeAll();
                        ElNotification.error({
                            title: t('message.prompt'),
                            message: message,
                            position: 'bottom-right',
                            zIndex:2015
                        });
                    }
                }
            }
        }else{
            if(!res.config.isReturn){
                if(isMobile()){
                    mobileMessage.closeAll()
                    mobileMessage.install({
                        text:message,
                        type:'error'
                    })
                }else{
                    ElNotification.closeAll();
                    ElNotification.error({
                        title: t('message.prompt'),
                        message: message,
                        position: 'bottom-right',
                        zIndex:2015
                    });
                }
            }
        }
        if(!res.config.isReturn){
            return Promise.reject(new Error(message));
        }else{
            return res;
        }
    }
    if(res.data && res.data.code == -3){
        if(!localStorage.getItem('hadRefresh') || localStorage.getItem('hadRefresh') == '') {
            if(userStore.access_token){
                localStorage.setItem('hadRefresh', new Date().getTime())
                router.go(0)
            }else{
                router.push({ path: "/" });          
            }
        }else{
            userStore.LogOut().then(() => {
                sessionStorage.setItem('lastUrl', lastUrl)
                if(router.currentRoute.value && router.currentRoute.value.path != '/') {
                    router.push({ path: "/" });
                }
                eventBus.$emit('loginEvent', 'loginOut')
            });
        }
        // return res
    }
    if(res.data && res.data.code === 20000){
        upgradeDialog.install({
            showBtn:false,
            message:res.data.msg
        })
    }
    if(res.data && res.data.code === -2) {
        if(res.config && whiteApi.indexOf(res.config.url) > -1) {
            userStore.LogOut().then(() => {
                sessionStorage.setItem('lastUrl', lastUrl)
                    if(router.currentRoute.value && router.currentRoute.value.path != '/') {
                    router.push({ path: "/" });
                }
                eventBus.$emit('loginEvent', 'loginOut')
            });
        }else{
            countTime += 1
        }
        let cancelArr = window.axiosCancel;
        for(let i in cancelArr) {
            delete window.axiosCancel[i]
        }
        if(countTime == 1 && localStorage.getItem('hadRefresh') == 'yes'){
            userStore.LogOut().then(() => {
                sessionStorage.setItem('lastUrl', lastUrl)
                router.push({ path: "/login" });
            });
        }
        if(countTime == 1  && (!localStorage.getItem('hadRefresh') || ( new Date().getTime() > localStorage.getItem('hadRefresh')))) {
            sessionStorage.setItem('lastUrl', lastUrl)
            userStore.refreshToken(userStore.tenantId).then(res => {
                location.reload()
            }).catch(() => {
                userStore.LogOut().then(() => {
                    sessionStorage.setItem('lastUrl', lastUrl)
                    if(router.currentRoute.value && router.currentRoute.value.path != '/') {
                        router.push({ path: "/" });
                    }
                    eventBus.$emit('loginEvent', 'loginOut')
                });
            })
        }
        return res
    }else{
        if(res.config && res.config.url === '/mgr/jvs-auth/index/menu/frame' && res.data && res.data.code != 0) {
            userStore.LogOut().then(() => {
                sessionStorage.setItem('lastUrl', lastUrl)
                if(router.currentRoute.value && router.currentRoute.value.path != '/') {
                    router.push({ path: "/" });
                }
                eventBus.$emit('loginEvent', 'loginOut')
            });
        }else{
            if(res.data && res.data.code == -1) {
                if(isMobile()){
                    mobileMessage.closeAll()
                    mobileMessage.install({
                        text:message,
                        type:'error'
                    })
                }else{
                    ElNotification.closeAll();
                    ElNotification.error({
                        title: t('message.prompt'),
                        message: message,
                        position: 'bottom-right',
                        zIndex:2015
                    });
                }
                return Promise.reject(new Error(message));
            // 如果授权码需要返回请在请求体上加上isReturn:true
            }else if(authErrorCode.indexOf(res.data.code+'')!=-1 && !res.config.isReturn){
                const authMessage = res.data.msg || authCode[res.data.code]
                if(isMobile()){
                    mobileMessage.closeAll()
                    mobileMessage.install({
                        text:authMessage,
                        type:'error'
                    })
                }else{
                    ElNotification.closeAll();
                    ElNotification.error({
                        title: t('message.prompt'),
                        message: authMessage,
                        position: 'bottom-right',
                        zIndex:2015
                    });
                }
                return Promise.reject(new Error(authMessage));
            }else{
                if(res.config && res.config.url && res.config.url.startsWith('/mgr') && typeof res.data.data == 'string') {
                    let tp = {
                        data: res.data.data
                    }
                    try {
                        let temp = decryption({
                            data: tp,
                            key: deCodeKey,
                            param: ["data"]
                        });
                        res.data.data = JSON.parse(temp.data)
                        console.log('解密', res.data.data);
                        
                    } catch (error) {

                    }
                }
                if(res.config.url == freshTokenUrl) {
                    if(res.data) {
                    if(typeof res.data.userDto == 'string') {
                        let tp = JSON.parse(JSON.stringify(res.data))
                        let temp = decryption({
                            data: tp,
                            key: deCodeKey,
                            param: ["userDto"]
                        })
                        res.data.userDto = JSON.parse(temp.userDto)
                    }
                    }
                }
                if(res.config.url == '/auth/token') {
                    if(res.data && res.data.code == 0 && res.data.data) {
                        if(res.data.data.userDto && typeof res.data.data.userDto == 'string') {
                            let tp = JSON.parse(JSON.stringify(res.data.data))
                            let temp = decryption({
                                data: tp,
                                key: deCodeKey,
                                param: ["userDto"]
                            })
                            res.data.data.userDto = JSON.parse(temp.userDto)
                        }
                    }
                }
                return res;
            }
        }
    }
  },
  (err) => {
    NProgress.done();
    if(new Error(err) == 'Error: Cancel'){
        return {data:{}}
    }else{
        return Promise.reject(new Error(err));
    }
  }
);
 
export default instance;